package org.ala.tiktools_clickhouse_generator.table;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *
 *	@author ala
 *	@date 2025年6月7日
 */
public class TableInfoParser {

	
	/**
	 * 	根据连接解析表信息
	 * @throws SQLException 
	 */
	public static TableInfo parseTableInfo(String tableName, Connection conn) throws SQLException {
		DatabaseMetaData metadata = conn.getMetaData();
		
		TableInfo ti = new TableInfo();
		ti.name = tableName;
		ti.setColumns(parseColumns(tableName, metadata));
		return ti;
	}
	
	/**
	 * 	遍历字段
	 * 	@throws SQLException 
	 */
	protected static List<ColumnInfo> parseColumns(String tableName, DatabaseMetaData metadata) throws SQLException {
		 ResultSet rs = metadata.getColumns(null, null, tableName, null);
		 List<ColumnInfo> fields = new ArrayList<>();
		 Set<String> set = new HashSet<>();
		 while (rs.next()) {
			 String column = rs.getString("COLUMN_NAME");
			 String type = rs.getString("TYPE_NAME");
			 Integer size = rs.getInt("COLUMN_SIZE");
			 String remark = rs.getString("REMARKS");
			 if (set.add(column)) {
				 fields.add(ColumnInfo.build(column, type, size, remark));
			 }
		 }
		 return fields;
	}
	
}
